package cn.conac.rc.itm.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.itm.entity.AelItemCatalogueEntity;
import cn.conac.rc.itm.repository.AelItemCatalogueRepository;
import cn.conac.rc.itm.vo.AelItemVo;

@Service
public class AelItemCatalogueService extends GenericService<AelItemCatalogueEntity, Integer> {

	@Autowired
	private AelItemCatalogueRepository catalogueRepository;

	/**
	 * 计数查询
	 *
	 * @param vo
	 * @return 计数结果
	 */
	public long count(AelItemVo vo) {
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 *
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<AelItemCatalogueEntity> findItemsByOrgId(AelItemVo vo) throws Exception {
		try {
			Sort sort = new Sort(Sort.Direction.DESC, "createTime");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<AelItemCatalogueEntity> dc = this.createCriteria(vo);
			return catalogueRepository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 *
	 * @param vo
	 * @return Criteria
	 */
	private Criteria<AelItemCatalogueEntity> createCriteria(AelItemVo vo) {
		Criteria<AelItemCatalogueEntity> dc = new Criteria<>();
		// 机构ID
		if (StringUtils.isNotBlank(vo.getOwnOrgId())) {
			dc.add(Restrictions.eq("objectIm", vo.getOwnOrgId(), true));
		}
		// 权力类别
		if (StringUtils.isNotBlank(vo.getItemType())) {
			dc.add(Restrictions.eq("itemType", vo.getItemType(), true));
		}
		// 权力事项名称
		if (StringUtils.isNotBlank(vo.getItemName())) {
			dc.add(Restrictions.like("itemName", vo.getItemName(), true));
		}
		// 对应地区ID
		if (StringUtils.isNotBlank(vo.getAreaId())) {
			dc.add(Restrictions.eq("areaId", vo.getAreaId(), true));
		}
		if(StringUtils.isNotBlank(vo.getUsers())){
			dc.add(Restrictions.eq("users",vo.getUsers(),true));
		}
		dc.add(Restrictions.ne("itemType", "1", true));
		return dc;
	}
}
